﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.IdentityModel.Tokens.Jwt;

namespace MvcClient
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); //这句话是指, 我们关闭了JWT的Claim 类型映射, 以便允许well-known claims.这样做, 就保证它不会修改任何从Authorization Server返回的Claims
            //注入该服务
            services.AddAuthentication(options =>
            {
                options.DefaultScheme = "Cookies";//使用Cookie作为验证用户的首选方式
                options.DefaultChallengeScheme = "oidc";//把DefaultChanllangeScheme设为"oidc"是因为, 当用户需要登陆的时候, 将使用的是OpenId Connect Scheme.
            })
            .AddCookie("Cookies")//添加了可以处理Cookie的处理器(handler)
            //AddOpenIdConnect是让上面的handler来执行OpenId Connect 协议.
            .AddOpenIdConnect("oidc", options =>
            {
                //一旦OpenId Connect协议完成, SignInScheme使用Cookie Handler来发布Cookie (中间件告诉我们已经重定向回到MvcClient了, 这时候有token了, 使用Cookie handler来处理).
                options.SignInScheme = "Cookies";
                options.Authority = "http://localhost:5000";//Authority是指信任的Identity Server ( Authorization Server).
                options.RequireHttpsMetadata = false;
                options.ClientId = "mvc_code";//ClientId是Client的识别标志
                options.ClientSecret = "secret";
                options.ResponseType = "id_token code";
                options.Scope.Add("socialnetwork");
                options.Scope.Add("offline_access");
                options.Scope.Add("email");
                options.SaveTokens = true;//SaveTokens为true表示要把从Authorization Server的Reponse中返回的token持久化在cookie中.
                options.GetClaimsFromUserInfoEndpoint = true;//从UserInfo节点获取用户的Claims
            });
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseAuthentication();//在管道配置的位置一定要在useMVC之前.

            app.UseStaticFiles();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
